package com.doupi.partner.dal.plugin;

import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import com.doupi.partner.util.ObjectUtils;

/**
 * 模型拦截器
 *
 * @author Super Jens Wang
 * @version 1.0 $id: ModelInterceptor.java 2015年9月20日 下午3:19:55 Wang Le $
 */
@Intercepts (@Signature (type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }))
public class ModelInterceptor implements Interceptor {
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		Object object = invocation.getArgs()[1];
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
			if (SqlCommandType.INSERT.equals(sqlCommandType)) {
				ObjectUtils.setFieldValue(object, "createAdministratorId", 1L);
			}
			ObjectUtils.setFieldValue(object, "updateAdministratorId", 1L);
			ObjectUtils.setFieldValue(object, "updateTime", null);
			ObjectUtils.setFieldValue(object, "createTime", null);
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {

	}

}
